﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Kooboo.HtmlFunc.Function;
using Kooboo.HtmlFunc.Providers;

namespace Kooboo.HtmlFunc.Analysis.Visitors
{
    public class InnerPageVisitor : StartEndVisitor
    {
        public InnerPageVisitor(VisitorContext context)
            : base(context, FuncType.InnerPage)
        {
        }

        private IFuncTester _startCommentTester;
        protected override IFuncTester StartCommentTester
        {
            get
            {
                if (_startCommentTester == null)
                    _startCommentTester = new Testers.ParametricTester(this.Func.StartComment);
                return _startCommentTester;
            }
        }

        protected override object OnQualified(HtmlCommentNode startNode, HtmlCommentNode endNode)
        {
            var tester = (Testers.ParametricTester)this.StartCommentTester;
            var pageName = tester.GetParameter("name");
            if (string.IsNullOrEmpty(pageName))
            {
                if (!this.Context.ThrowException)
                    return null;
                throw new Exceptions.ParameterEmptyException(this.Context.FileName, startNode, "name");
            }

            var innerPageList = this.Context.Items[FuncType.None] as List<IInnerPage>;
            if (innerPageList.Count(o => o.Name.IgnoreCaseEquals(pageName)) > 0)
            {
                if (!this.Context.ThrowException)
                    return null;
                throw new Exceptions.ParameterValueExistingException(this.Context.FileName, startNode, "name", pageName);
            }

            // add
            var innerPage = Provider.Factory.GetProvider<IInnerPage>();
            innerPage.StartNode = startNode;
            innerPage.EndNode = endNode;
            innerPage.Name = pageName;
            innerPageList.Add(innerPage);

            // ret context mark
            return innerPage;
        }

        protected override FuncType ExclusiveType
        {
            get
            {
                return this.FuncType
                    | FuncType.Position
                    | FuncType.Label
                    | FuncType.HtmlBlockPart
                    | FuncType.HtmlPart
                    | FuncType.ViewPart
                    | FuncType.Menu
                    | FuncType.Detail
                    | FuncType.List;
            }
        }
    }
}
